<template>
  <div>
    <div style="display: flex">
      <el-input v-model="filterText" style="width: 200px" @clear="handlerCateFilterClear" clearable
                placeholder="请输入关键词"/>
      <el-button @click="handlerRefreshCate" type="danger" circle class="ml8">
        <el-icon>
          <ele-RefreshLeft/>
        </el-icon>
      </el-button>

      <el-button @click="appendCate" type="danger" circle class="ml8">
        <el-icon>
          <ele-Plus/>
        </el-icon>
      </el-button>
    </div>
    <el-tree ref="treeRef"
             style="margin-top: 20px;max-height: 700px;overflow: auto"
             :data="cateData"
             node-key="id"
             :props="cateProps"
             :expand-on-click-node="false"
             default-expand-all
             :filter-node-method="filterNode"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span class="cate-title" @click="handlerNodeClick(data)">{{ node.label }}</span>
          <span>
<!--            <el-button type="primary" link @click="appendCate(data)"> 添加 </el-button>-->
            <el-button v-if="data.id !== '0'" type="primary" link @click="editCate(data)"> 编辑 </el-button>
            <el-button v-if="data.id !== '0'" type="danger" link style="margin-left: 8px"
                       @click="removeCate(node, data)"> 删除 </el-button>
          </span>
        </span>
      </template>

    </el-tree>

    <DictCateItemDialog @refresh="getCateData" ref="dictCateItemDialogRef"></DictCateItemDialog>
  </div>
</template>


<script setup>
import {defineAsyncComponent, onMounted, ref, watch} from "vue";
import {useQuesApi} from "/@/api/ques";
import {ElMessage, ElMessageBox} from "element-plus";

const DictCateItemDialog = defineAsyncComponent(() => import('/@/components/cate/dialog.vue'));

const quesApi = useQuesApi()

const dictCateItemDialogRef = ref();
const treeRef = ref();

const filterText = ref('')
const crtCateId = ref('')
const cateData = ref([])


const props = defineProps({
  dicType: {
    type: String,
    default: () => {
      return ''
    }
  }
})

const cateProps = ref(
    {
      children: 'children',
      label: 'label',
    }
)

const emit = defineEmits(['onCateClick'])

const handlerCateFilterClear = () => {
  crtCateId.value = ''
  emit('onCateClick', '')
}


const handlerRefreshCate = () => {
  getCateData()
}


const filterNode = (value, data) => {
  if (!value) return true
  return data.label?.includes(value)
}

// 分类点击
const handlerNodeClick = (data) => {
  if (crtCateId.value === data.id) {
    return
  }

  crtCateId.value = data.id
  if (data.id === '0') {
    emit('onCateClick', '')
  } else {
    emit('onCateClick', crtCateId.value)
  }

}


const appendCate = () => {
  dictCateItemDialogRef.value.openDialog('add', props.dicType);
}

const editCate = (data) => {
  dictCateItemDialogRef.value.openDialog('edit', props.dicType, data.parentId, data.id);
}

const removeCate = (node, data) => {

  ElMessageBox.confirm(`您确认要删除吗，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        quesApi.cateDelete(data.id).then(() => {
          ElMessage.success("删除成功")
          // getCateData();


          let delInx = -1;
          for (let i = node.parent.data.children.length - 1; i >= 0; i--) {
            let item = node.parent.data.children[i]
            if (item.id === data.id) {
              delInx = i;
            }
          }

          if (delInx > -1) {
            node.parent.data.children.splice(delInx, 1)
          }
          return

        });
      })
      .catch(() => {
      });
}


// 获取分类数据
const getCateData = () => {
  if (!props.dicType) {
    ElMessage.error("dicType不能为空")
    return
  }
  quesApi.cateTree().then((res) => {
    cateData.value = [res.data];
  });
};

onMounted(() => {
  getCateData()
  crtCateId.value = ''
})



watch(filterText, (val) => {
  treeRef.value?.filter(val)
})


</script>

<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .cate-title {
    flex: 1;
  }
}
</style>